<template>
  <!--维保计划生成任务--创建维保计划-->
  <div class="page-operate">
    <!-- 位置模块 -->
    <HeadTop></HeadTop>
    <div class="page-head">
      <span class="operate-text">创建维保计划 (已选择<i style="color:#d9534f;">{{eleNum}}</i>台电梯)</span>
      <div class="operate-box">
        <button @click="submitForm('myForm')" v-show="editAble" class="submit">提交</button>
        <button @click="back()">关闭</button>
      </div>
    </div>
    <div class="content-area">
      <div class="main-content form-edit form-edit-task">
        <div class="search-form">
          <el-form class="my-form my-form-300 add-task" ref="myForm" :rules=rules :model="myForm" :inline="true"
                   size="medium" node-key="id">
            <el-form-item label="计划维保时间:" :class="planDateErrorShow?'is-error':''" required>
              <el-date-picker v-model="myForm.planDate" align="right" type="date" placeholder="选择计划维保日期" :readonly="onlyRead" @change="plantDateChange">
              </el-date-picker>
              <div class="el-form-item__error" v-show="planDateErrorShow">{{planDateError}}</div>
            </el-form-item>
            <el-form-item label="维保类型:" required prop="maintainTypeId">
              <el-select v-model="myForm.maintainTypeId" placeholder="--请选择维保类型--" @change="relationCheck" clearable>
                <el-option v-for="item in maintainTypeArr" :key="item.id" :label="item.name"
                           :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <div class="page-form add-plain">
          <div class="item-title">
            <span>{{currentMain}}</span>
          </div>
          <el-form class="my-form check-form" :inline="true">
            <el-tree :data="topList" class="tree hidden" show-checkbox default-expand-all node-key="id" ref="tree1"  empty-text="暂无数据,请选择维保类型"
                     highlight-current :props="defaultProps">
            </el-tree>
          </el-form>
        </div>
        <div class="page-form add-plain">
          <div class="item-title">
            <span>所有维保项目</span>
            <!--<span class="all" :class="{ check: allCheck }" v-model="allCheck" @click="check">-->
            <!--<span></span>-->
            <!--</span>-->
            <!--<span>全选</span>-->
          </div>
          <el-form class="my-form check-form" :inline="true">
            <el-tree :data="itemList" class="tree" show-checkbox default-expand-all node-key="id" ref="tree2"
                     highlight-current :props="defaultProps" @check-change="treeCheckChange">
            </el-tree>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>
<style lang="scss" type="text/scss">
  @import '../../../../style/entry/components/pageChildCommon';
  @import '../../../../style/entry/page/taskAdd';
  .tree.hidden .el-tree__empty-text {
    color: #8F9399;
  }
</style>
<script>
  // 引入区域选择组件
  import areaSelect from "../../../../components/areaSelect/areaSelect"
  import com from "../../../../js/common"
  // 时间插件
  import moment from 'moment'
  import HeadTop from "../../../../components/head-top/head-top"
  import {
    getMaintainItemAll,
    getEleType,
    getMaintainType,
    maintainTaskDetail,
    maintainTaskAdd,
    maintainTaskEdit,
    maintainItemByType
  } from '@/api/getData'

  export default {
    data() {
      return {
        allCheck: false,
        title: '',
        type: 'add',
        onlyRead: false,
        planDateErrorShow: false,
        planDateError: '请选择计划维保时间',
        eleNum: 1, // 已选择电梯数量
        myForm: {
          planDate: '',
          maintainTypeId: '',
          elCodeList: [],
          idList: [],

        },
        editAble: true,
        // 所有维保类型
        maintainAll: [],
        // 选中维保类型
        topList: [],
        currentMain: '维保类型',
        maintainTypeArr: [],
        maintainTypeIds: [],
        // 选中的电梯code
        taskEleCode: [],
        eleTypeArr: [],
        areaArr: [],
        itemList: [],
        defaultProps: {
          children: 'itemList',
          label: 'item'
        },
        defaultProp: {
          children: 'itemList',
          label: 'item'
        },
        rules: {
          maintainTypeId: [
            {required: true, message: '请选择维保类型'}
          ],
        },
        areaText: '',
        areaCode: ''
      }

    },
    components: {
      areaSelect,
      HeadTop
    },
    //
    mounted(){
      let isOne = this.$route.query.code ? this.$route.query.code : false;
      let code = com.getStore('taskEleCode') ? JSON.parse(com.getStore('taskEleCode')): false;
      let eleCode = [];
      if(isOne){
        eleCode[0] = isOne
      }else{
        if(code){
          let num= 0;
          code.forEach(function(e, i){
            if(e){
              e.forEach(function(f, j){
                num += 1;
                eleCode.push(f);
              })
            }
          })
          this.eleNum = num;
        }
      }
      this.myForm.elCodeList = eleCode;
    },

    // 页面装载中,此时获取后端数据
    created() {
      // 获取当前页面所需维保项目数据
      this.getItemsData();

      // 获取当前页面所需维保类型数据
      this.getMaintainTypeData();
    },
    methods: {
      // 选择计划维保时间的校验：1.不能为空 2.不能大与当前时间
      plantDateChange(val) {
        let nowTime = Date.parse(new Date());
        if(!val){
          this.planDateErrorShow = true;
          this.planDateError = '请选择计划维保时间';
        } else if (moment(val).isBefore(nowTime)) {
          this.planDateErrorShow = true
          this.planDateError = '计划维保时间应大于当前时间';
        } else {
          this.planDateErrorShow = false;
        }
      },
      // 获取页面所需维保项目数据
      getItemsData(obj) {
        getMaintainItemAll({}).then((data) => {
          let info = data.data.data;
          info.forEach(function (i, e) {
            i.id = parseInt(i.id) + 10000;
          });
          this.itemList = info;
        }).catch((err) => {
          this.$message.error('查询维保项目数据失败');
        })
      },

      // 获取当前页面所需维保类型数据
      getMaintainTypeData() {
        getMaintainType({}).then((data) => {
          let info = data.data.data;
          let maintainTypeArr = [];
          info.forEach(function (i, e) {
            if (e < 4) {
              maintainTypeArr.push({'name': i.name, 'id': i.id})
            }
          })
          this.maintainTypeArr = maintainTypeArr;
        }).catch((err) => {
          if (this.type != 'detail') this.$message.error('查询维保类型数据失败');
        })
      },

      // 表单数据的校验
      submitForm(form) {
        this.$refs[form].validate((valid) => {
          if (valid) {
            this.plantDateChange(this.myForm.planDate);
            let arr = [];
            let arr1 = this.$refs.tree1.getCheckedKeys();
            const arr2 = this.$refs.tree2.getCheckedKeys();
            arr1.push(...arr2);
            for(const i in arr1){
              if(arr1[i]<10000){
                arr.push(arr1[i]);
              }
            }
            this.myForm.idList = arr;
            if (!this.planDateErrorShow) this.addplain();
          } else {
            return false;
          }
        });
      },

      // 创建维保计划生成任务
      addplain() {
        maintainTaskAdd(this.myForm).then((res) => {
          com.mask()
          this.axioThen(this);
        }).catch((err) => {
          this.$message.error('操作失败: ' + err.data.message)
        })
      },

      // 編輯/添加維保計劃生成任務成功后的操作
      axioThen(self) {
        self.$message.success({
          message: '操作成功',
          duration: 1500,
          onClose: () => {
            com.unmask()
            com.setStore('taskEleCode', '');
            self.$router.push('/manage/maintainMgr/plainTask')
          }
        });
      },

      // 获取查询地址
      getArea(res) {
        this.myForm.areaCode = res.code
      },

      // 选择维保类型是 关联勾选维保项目选择框
      relationCheck(val) {
        if(val){
          const maintainTypeObj = {1: '半月维保', 2: '季度维保', 3: '半年维保', 4: '年度维保'};
          maintainItemByType({typeId: val}).then((res) => {
            let list = [];
            let itemIds = [];
            let info = res.data.data;
            list[0] = { id: val+10000, item: maintainTypeObj[val], itemList: info};
            info.forEach(function (i) {
              itemIds.push(i.id)
            });
            this.currentMain = maintainTypeObj[val];
            this.topList = list;
            this.$refs.tree1.setCheckedKeys(itemIds);
          }).catch((err) => {
            this.$message.error('操作失败: ' + err.data.message);
          })
        }else{
          this.currentMain = '维保类型';
          this.topList = [];
        }
      },

      // treeCheckChange
      treeCheckChange(data, checked, indeterminate){
        if(!this.myForm.maintainTypeId){
          this.$message.warning('请先选择维保类型')
          this.$refs.tree2.setCheckedKeys([]);
        }
      },

      // 返回上一级
      back() {
        this.$router.go(-1);
      },
    },
  };
</script>
